package com.fanh.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;



public class CommonUtil {
    //生成随机用户名，数字和字母组成,
    public static String getStringRandom(int length) {
                 String val = "";
                 Random random = new Random();

                 //参数length，表示生成几位随机数
                 for(int i = 0; i < length; i++) {

                         String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
                         //输出字母还是数字
                         if( "char".equalsIgnoreCase(charOrNum) ) {
                                 //输出是大写字母还是小写字母
                                 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                                 val += (char)(random.nextInt(26) + temp);
                             } else if( "num".equalsIgnoreCase(charOrNum) ) {
                                 val += String.valueOf(random.nextInt(10));
                             }
                     }
                 return val;
             }


    //获取客户端IP地址
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");

            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");

            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");

            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");

            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();

            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }

        return ip;
    }

    public static JSONObject doGet(String url) throws Exception {
        //调用发分层接口
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        System.out.println("去计算分成");
        HttpGet httpGet = new HttpGet(url);
        //3.发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4.判断状态码
        String string = null;
        JSONObject jb = null;

        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            //使用工具类EntityUtils，从响应中取出实体表示的内容并转换成字符串
            string = EntityUtils.toString(entity, "utf-8");
            jb = JSONObject.parseObject(string);
            System.out.println(string);
        }
        //5.关闭资源
        response.close();
        httpClient.close();
        return  jb;
    }

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
     */
    public static String uuid() {
        return java.util.UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code
                + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }



    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };


    /**
     * 发送请求
     *
     * @param url
     * @param
     * @return
     */
    public static String sendHttpsCoon(String url, String code) {
        if (url.isEmpty()) {
            return null;
        }
        try {
            // 设置SSLContext
            SSLContext ssl = SSLContext.getInstance("SSL");
            ssl.init(null, new TrustManager[]{myX509TrustManager}, null);

            // 打开连接
            HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
            // 设置套接工厂
            conn.setSSLSocketFactory(ssl.getSocketFactory());
            // 加入数据
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-type", "application/json");

            JSONObject obj = new JSONObject();
            obj.put("receipt-data", code);

            BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
            buffOutStr.write(obj.toString().getBytes());
            buffOutStr.flush();
            buffOutStr.close();

            // 获取输入流
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();

        } catch (Exception e) {
            return null;
        }
    }



    public static void main(String[] args) {

     //   System.out.println(StringUtil.isEmpty(null));
        /*Map map = new HashMap();
        Map map2=null;
        System.out.println("map:"+map.isEmpty());
       // System.out.println("map2:"+map2.isEmpty());

        System.out.println("map:"+map.get(1));
        System.out.println("map2:"+map2.get(1));*/
        //System.out.println(getStringRandom(10));

      /*  BigDecimal one= new BigDecimal(0.00);
        BigDecimal two= new BigDecimal(0);
        BigDecimal three= new BigDecimal(0.00);
        System.out.println(one.compareTo(two));
        System.out.println(one.compareTo(three));
*/
     /* String url ="https://thirdwx.qlogo.cn/mmopen/vi_32/0kxvN4XicIzKAvXOriaJqPhVoGeMzd8tGOUN9iahuzxlw56xSuNNRxp5yibx5sdSPnw8pJm4VW8noY8NiataeZ5m3ng/132";
      String newUrl=url.replace("thirdwx.qlogo.cn","shenlanhui.inklingedu.com");
      System.out.println(url);
        System.out.println(newUrl);*/



    }
}
